package com.atguigu.srb.core.service.impl;

import com.atguigu.srb.common.exception.Assert;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.core.enums.UserBindEnum;
import com.atguigu.srb.core.hfb.FormHelper;
import com.atguigu.srb.core.hfb.HfbConst;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.pojo.entity.UserBind;
import com.atguigu.srb.core.mapper.UserBindMapper;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.pojo.vo.UserBindVO;
import com.atguigu.srb.core.service.UserBindService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户绑定表 服务实现类
 * </p>
 *
 * @author HuoYongZhuang
 * @since 2021-06-17
 */
@Service
public class UserBindServiceImpl extends ServiceImpl<UserBindMapper, UserBind> implements UserBindService {

//    eq 就是 equal等于
//    ne就是 not equal不等于
//    gt 就是 greater than大于
//    lt 就是 less than小于
//    ge 就是 greater than or equal 大于等于
//    le 就是 less than or equal 小于等于
//    in 就是 in 包含（数组）
//    isNull 就是 等于null
//    between 就是 在2个条件之间(包括边界值)
//    like就是 模糊查询

    @Resource
    private UserInfoMapper userInfoMapper;


    @Override
    public String commitBindUser(UserBindVO userBindVO, Long userId) {

        //不同的user_id,相同的身份证，如果存在，则不允许
        QueryWrapper<UserBind> userBindQueryWrapper = new QueryWrapper<>();
        userBindQueryWrapper.eq("id_card",userBindVO.getIdCard())
                .ne("user_id",userId);
        UserBind userBind = baseMapper.selectOne(userBindQueryWrapper);
        //USER_BIND_IDCARD_EXIST_ERROR(-301, "身份证号码已绑定"),
        Assert.isNull(userBind, ResponseEnum.USER_BIND_IDCARD_EXIST_ERROR);


        //用户是否曾经绑定过表单
        userBindQueryWrapper = new QueryWrapper<>();
        userBindQueryWrapper.eq("user_id",userId);
        baseMapper.selectOne(userBindQueryWrapper);
        if (userBind == null){
            //创建用户绑定记录
            userBind = new UserBind();
            BeanUtils.copyProperties(userBindVO,userBind);
            userBind.setUserId(userId);
            userBind.setStatus(UserBindEnum.NO_BIND.getStatus());
            baseMapper.insert(userBind);
        }else {
            //相同的user_id，如果存在，那么就去除数据，做更新
            BeanUtils.copyProperties(userBindVO,userBind);
            baseMapper.updateById(userBind);
        }


        //传统的生成动态表单模版字符串，现在用不到
        String form = "<html lang=\"en\" xmlns:th=\"http://www.thymeleaf.org\">\n" +
                "  <head> </head>\n" +
                "  <body>\n" +
                "    <form name=\"form\" action=\"远程地址\" method=\"post\">\n" +
                "      <!-- 参数 -->\n" +
                "      <input type=\"text\" name=\"mobile\" value=\""+userBindVO.getMobile()+"\" />\n" +
                "      <input type=\"text\" name=\"sign\" value=\"123456\" />\n" +
                "    </form>\n" +
                "    <script>\n" +
                "      document.form.submit()\n" +
                "    </script>\n" +
                "  </body>\n" +
                "</html>" ;


        //组装自动提交表单的参数
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("agentId", HfbConst.AGENT_ID);
        paramMap.put("agentUserId", userId);
        paramMap.put("idCard",userBindVO.getIdCard());
        paramMap.put("personalName", userBindVO.getName());
        paramMap.put("bankType", userBindVO.getBankType());
        paramMap.put("bankNo", userBindVO.getBankNo());
        paramMap.put("mobile", userBindVO.getMobile());
        paramMap.put("returnUrl", HfbConst.USERBIND_RETURN_URL);
        paramMap.put("notifyUrl", HfbConst.USERBIND_NOTIFY_URL);
        paramMap.put("timestamp", RequestHelper.getTimestamp());
        paramMap.put("sign", RequestHelper.getSign(paramMap));
        //通过封装的工具类
        String formStr = FormHelper.buildForm(HfbConst.USERBIND_URL, paramMap);


        return formStr;
    }
   @Transactional(rollbackFor = Exception.class)
    @Override
    public void notify(Map<String, Object> paramMap) {
        String bindCode = (String)paramMap.get("bindCode");
        String agentUserId= (String)paramMap.get("agentUserId");

        //更新用户绑定表
        //1。先根据user_id查询userBind记录
        QueryWrapper<UserBind> userBindQueryWrapper = new QueryWrapper<>();
        userBindQueryWrapper.eq("user_id",agentUserId);
        UserBind userBind = baseMapper.selectOne(userBindQueryWrapper);
        //2。更新用户绑定表
        userBind.setBindCode(bindCode);
        userBind.setStatus(UserBindEnum.BIND_OK.getStatus());
        baseMapper.updateById(userBind);

        //更新用户表
//        1。先查询出userInfo对象
        UserInfo userInfo = userInfoMapper.selectById(agentUserId);
        userInfo.setBindCode(bindCode);
        userInfo.setName(userBind.getName());
        userInfo.setIdCard(userBind.getIdCard());
        userInfo.setBindStatus(UserBindEnum.BIND_OK.getStatus());
//        2.更新用户表
        userInfoMapper.updateById(userInfo);


    }

    @Override
    public String getBindCodeByUserId(Long userId) {
        QueryWrapper<UserBind> userBindQueryWrapper = new QueryWrapper<>();
        userBindQueryWrapper.eq("user_id", userId);
        UserBind userBind = baseMapper.selectOne(userBindQueryWrapper);
        String bindCode = userBind.getBindCode();
        return bindCode;
    }
}
